{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Transfering knowledge through finetuning \n",
    "\n",
    "In previous chapters, \n",
    "we demonstrated how to train a neural network \n",
    "to recognize the categories corresponding to objects in images.\n",
    "We looked at toy datasets like hand-written digits,\n",
    "and thumbnail-sized pictures of animals. \n",
    "And we talked about the ImageNet dataset, \n",
    "the default academic benchmark,\n",
    "which contains 1M million images,\n",
    "1000 each from 1000 separate classes.\n",
    "\n",
    "The ImageNet dataset categorically changed what was possible in computer vision.\n",
    "It turns out some things are possible (these days, even easy) \n",
    "on gigantic datasets, that simply aren't with smaller datasets.\n",
    "In fact, we don't know of any technique that can comparably powerful model\n",
    "on a similar photograph dataset but containing only, say, 10k images.\n",
    "\n",
    "And that's a problem. \n",
    "Because however impressive the results of CNNs on ImageNet may be,\n",
    "most people aren't interested in ImageNet itself.\n",
    "They're interested in their own problems.\n",
    "Recognize people based on pictures of their faces.\n",
    "Distinguish between photographs of $10$ different types of coral on the ocean floor. \n",
    "Usually when individuals (and not Amazon, Google, or inter-institutional *big science* initiatives)\n",
    "are interested in solving a computer vision problem,\n",
    "they come to the table with modestly sized datasets. \n",
    "A few hundred examples may be common and a few thousand examples may be as much as you can reasonably ask for.\n",
    "\n",
    "So one natural question emerges.\n",
    "Can we somehow use the powerful models trained on millions of examples for one dataset,\n",
    "and apply them to improve performance on a new problem \n",
    "with a much smaller dataset?\n",
    "This kind of problem (learning on source dataset, bringing knowledge to target dataset),\n",
    "is appropriately called *transfer learning*. \n",
    "Fortunately, we have some effective tools for solving this problem.\n",
    "\n",
    "For deep neural networks, the most popular approach is called finetuning\n",
    "and the idea is both simple and effective:\n",
    "\n",
    "* Train a neural network on the source task $S$.\n",
    "* Decapitate it, replacing it's output layer appropriate to target task $T$.\n",
    "* Initialize the weights on the new output layer randomly, keeping all other (pretrained) weights the same.\n",
    "* Begin training on the new dataset.\n",
    "\n",
    "This might be clearer if we visualize the algorithm: \n",
    "\n",
    "![](../img/fine-tune.png)\n",
    "\n",
    "\n",
    "In this section, we'll demonstrate fine-tuning,\n",
    "using the popular and compact SqueezeNet architecture.\n",
    "Since we don't want to saddle you with the burden of downloading ImageNet,\n",
    "or of training on ImageNet from scratch,\n",
    "we'll pull the weights of the pretrained Squeeze net from the internet.\n",
    "Specifically, we'll be fine-tuning a squeezenet-1.1 \n",
    "that was pre-trained on imagenet-12.\n",
    "Finally, we'll fine-tune it to recognize **hotdogs**."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![hot dog](../img/comic-hot-dog.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll start with the obligatory ritual of importing a bunch of stuff that you'll need later. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pylab inline\n",
    "pylab.rcParams['figure.figsize'] = (10, 6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Settings\n",
    "We'll set a few settings up here that you can configure later to manipulate the behavior of the algorithm. \n",
    "These are mostly familiar. \n",
    "Hybrid mode, uses the just in time compiler described in [our chapter on high performance training](../chapter07_distributed-learning/hybridize.ipynb)\n",
    "to make the network much faster to train. \n",
    "Since we're not working with any crazy dynamic graphs that can't be compiled, \n",
    "there's no reason not to hybridize. \n",
    "The batch size, number of training epochs, weight decay, and learing rate should all be familiar by now.\n",
    "The positive class weight, says how much more we should upweight the importance of positive instances (photos of hot dogs) in the objective function. \n",
    "We use this to combat the extreme class imbalance (not surprisingly, most pictures do not depict hot dogs). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Demo mode uses the validation dataset for training, which is smaller and faster to train.\n",
    "demo = True\n",
    "log_interval = 100\n",
    "\n",
    "# Options are imperative or hybrid. Use hybrid for better performance.\n",
    "mode = 'hybrid'\n",
    "\n",
    "# training hyperparameters\n",
    "batch_size = 256\n",
    "if demo:\n",
    "    epochs = 5\n",
    "    learning_rate = 0.02\n",
    "    wd = 0.002\n",
    "else:\n",
    "    epochs = 40\n",
    "    learning_rate = 0.05\n",
    "    wd = 0.002\n",
    "\n",
    "# the class weight for hotdog class to help the imbalance problem.\n",
    "positive_class_weight = 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "import logging\n",
    "logging.basicConfig(level=logging.INFO)\n",
    "import os\n",
    "import time\n",
    "from collections import OrderedDict\n",
    "import skimage.io as io\n",
    "\n",
    "import mxnet as mx\n",
    "from mxnet.test_utils import download\n",
    "mx.random.seed(127)\n",
    "\n",
    "# setup the contexts; will use gpus if avaliable, otherwise cpu\n",
    "gpus = mx.test_utils.list_gpus()\n",
    "contexts = [mx.gpu(i) for i in gpus] if len(gpus) > 0 else [mx.cpu()]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataset\n",
    "Formally, hot dog recognition is a binary classification problem.\n",
    "We'll use $1$ to represent the hotdog class, \n",
    "and $0$ for the *not hotdog* class. \n",
    "Our hot dog dataset (the target dataset which we'll fine-tune the model to)\n",
    "contains 18,141 sample images, 2091 of which are hotdogs.\n",
    "Because the dataset is imbalanced (e.g. hotdog class is only 1% in mscoco dataset), \n",
    "sampling interesting negative samples can help to improve the performance of our algorithm. \n",
    "Thus, in the negative class in the our dataset, \n",
    "two thirds are images from food categories (e.g. pizza) other than hotdogs, \n",
    "and 30% are images from all other categories.\n",
    "\n",
    "### Files\n",
    "We prepare the dataset in the format of MXRecord using [im2rec](http://mxnet.io/how_to/recordio.html?highlight=im2rec) tool. As of the current draft, rec files are not yet explained in the book, but if you're reading after November or December 2017 and you still see this note, [open an issue on GitHub](https://github.com/zackchase/mxnet-the-straight-dope) and let us know to stop slacking off. \n",
    "\n",
    "- not_hotdog_train.rec 641M (1882 positive, 10000 interesting negative, and 5000 random negative)\n",
    "- not_hotdog_validation.rec 49M (209 positive, 700 interesting negative, and 350 random negative)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset_files = {'train': ('not_hotdog_train-e6ef27b4.rec', '0aad7e1f16f5fb109b719a414a867bbee6ef27b4'),\n",
    "                 'validation': ('not_hotdog_validation-c0201740.rec', '723ae5f8a433ed2e2bf729baec6b878ac0201740')}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To demo the model here, we're justgoing to use the smaller validation set.\n",
    "But if you're interested in training on the full set, \n",
    "set 'demo' to False in the settings at the beginning.\n",
    "Now we're ready to download and verify the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if demo:\n",
    "    training_dataset, training_data_hash = dataset_files['validation']\n",
    "else:\n",
    "    training_dataset, training_data_hash = dataset_files['train']\n",
    "\n",
    "validation_dataset, validation_data_hash = dataset_files['validation']\n",
    "\n",
    "def verified(file_path, sha1hash):\n",
    "    import hashlib\n",
    "    sha1 = hashlib.sha1()\n",
    "    with open(file_path, 'rb') as f:\n",
    "        while True:\n",
    "            data = f.read(1048576)\n",
    "            if not data:\n",
    "                break\n",
    "            sha1.update(data)\n",
    "    matched = sha1.hexdigest() == sha1hash\n",
    "    if not matched:\n",
    "        logging.warn('Found hash mismatch in file {}, possibly due to incomplete download.'\n",
    "                     .format(file_path))\n",
    "    return matched\n",
    "\n",
    "url_format = 'https://apache-mxnet.s3-accelerate.amazonaws.com/gluon/dataset/{}'\n",
    "if not os.path.exists(training_dataset) or not verified(training_dataset, training_data_hash):\n",
    "    logging.info('Downloading training dataset.')\n",
    "    download(url_format.format(training_dataset),\n",
    "             overwrite=True)\n",
    "if not os.path.exists(validation_dataset) or not verified(validation_dataset, validation_data_hash):\n",
    "    logging.info('Downloading validation dataset.')\n",
    "    download(url_format.format(validation_dataset),\n",
    "             overwrite=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Iterators\n",
    "\n",
    "The record files can be read using [mx.io.ImageRecordIter](https://mxnet.incubator.apache.org/api/python/io/io.html#mxnet.io.ImageRecordIter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load dataset\n",
    "train_iter = mx.io.ImageRecordIter(path_imgrec=training_dataset,\n",
    "                                   min_img_size=256,\n",
    "                                   data_shape=(3, 224, 224),\n",
    "                                   rand_crop=True,\n",
    "                                   shuffle=True,\n",
    "                                   batch_size=batch_size,\n",
    "                                   max_random_scale=1.5,\n",
    "                                   min_random_scale=0.75,\n",
    "                                   rand_mirror=True)\n",
    "val_iter = mx.io.ImageRecordIter(path_imgrec=validation_dataset,\n",
    "                                 min_img_size=256,\n",
    "                                 data_shape=(3, 224, 224),\n",
    "                                 batch_size=batch_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The model we are finetuning is [SqueezeNet](https://arxiv.org/abs/1602.07360). Gluon module offers squeezenet v1.0 and v1.1 that are pretrained on ImageNet. This is just a convolutional neural network, with an architecture chosen to have a small number of parameters and to require a minimal amount of computation. It's especially popular for folks that need to run CNNs on low-powered devices like cell phones and other internet-of-things devices.\n",
    "\n",
    "## Pulling the pre-trained model\n",
    "Fortunately, MXNet has a model zoo that gives us convenient access to a number of popular models,\n",
    "both their architectres and their pretrained parameters.\n",
    "Let's download SqueezeNet right now with just a few lines of code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet.gluon import nn\n",
    "from mxnet.gluon.model_zoo import vision as models\n",
    "\n",
    "# get pretrained squeezenet\n",
    "net = models.squeezenet1_1(pretrained=True, prefix='deep_dog_', ctx=contexts)\n",
    "# hot dog happens to be a class in imagenet.\n",
    "# we can reuse the weight for that class for better performance\n",
    "# here's the index for that class for later use\n",
    "imagenet_hotdog_index = 713"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### DeepDog net\n",
    "\n",
    "We can now use the feature extractor part from the pretrained squeezenet to build our own network. The model zoo, even handles the decaptiation for us. All we have to do is specify the number out of output classes in our new task, which we do via the keyword argument `classes=2`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "deep_dog_net = models.squeezenet1_1(prefix='deep_dog_', classes=2)\n",
    "deep_dog_net.collect_params().initialize(ctx=contexts)\n",
    "deep_dog_net.features = net.features\n",
    "print(deep_dog_net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The network can already be used for prediction. However, since it hasn't been finetuned yet, the network performance could be bad."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from skimage.color import rgba2rgb\n",
    "\n",
    "def classify_hotdog(net, url, contexts):\n",
    "    I = io.imread(url)\n",
    "    if I.shape[2] == 4:\n",
    "        I = rgba2rgb(I)\n",
    "    image = mx.nd.array(I).astype(np.uint8)\n",
    "    plt.subplot(1, 2, 1)\n",
    "    plt.imshow(image.asnumpy())\n",
    "    image = mx.image.resize_short(image, 256)\n",
    "    image, _ = mx.image.center_crop(image, (224, 224))\n",
    "    plt.subplot(1, 2, 2)\n",
    "    plt.imshow(image.asnumpy())\n",
    "    image = mx.image.color_normalize(image.astype(np.float32)/255,\n",
    "                                     mean=mx.nd.array([0.485, 0.456, 0.406]),\n",
    "                                     std=mx.nd.array([0.229, 0.224, 0.225]))\n",
    "    image = mx.nd.transpose(image.astype('float32'), (2,1,0))\n",
    "    image = mx.nd.expand_dims(image, axis=0)\n",
    "    out = mx.nd.SoftmaxActivation(net(image.as_in_context(contexts[0])))\n",
    "    print('Probabilities are: '+str(out[0].asnumpy()))\n",
    "    result = np.argmax(out.asnumpy())\n",
    "    outstring = ['Not hotdog!', 'Hotdog!']\n",
    "    print(outstring[result])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "classify_hotdog(deep_dog_net, '../img/real_hotdog.jpg', contexts)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Reuse class weights\n",
    "As mentioned earlier, in addition to the feature extractor, we can reuse the class weights for hot dog from the pretrained model, since hot dog was already a class in the imagenet. To do that, we need to get the weight from the classifier layers of the pretrained model, find the right slice, and put it into our two-class classifier."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# let's examine the output layer and find the last conv layer\n",
    "print(net.output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# the last conv layer is the second layer\n",
    "pretrained_conv_params = net.output[0].params\n",
    "\n",
    "# weights can then be found from the above parameter dict\n",
    "pretrained_weight_param = pretrained_conv_params.get('weight')\n",
    "pretrained_bias_param = pretrained_conv_params.get('bias')\n",
    "\n",
    "# next, we locate the right slice that we're interested in.\n",
    "hotdog_w = mx.nd.split(pretrained_weight_param.data(ctx=contexts[0]),\n",
    "                       1000, axis=0)[imagenet_hotdog_index]\n",
    "hotdog_b = mx.nd.split(pretrained_bias_param.data(ctx=contexts[0]),\n",
    "                       1000, axis=0)[imagenet_hotdog_index]\n",
    "\n",
    "# our classifier is for two classes. here, we reuse the hotdog class weight,\n",
    "# and randomly initialize the 'not hotdog' class.\n",
    "new_classifier_w = mx.nd.concat(mx.nd.random_normal(shape=hotdog_w.shape, scale=0.02, ctx=contexts[0]),\n",
    "                                hotdog_w,\n",
    "                                dim=0)\n",
    "new_classifier_b = mx.nd.concat(mx.nd.random_normal(shape=hotdog_b.shape, scale=0.02, ctx=contexts[0]),\n",
    "                                hotdog_b,\n",
    "                                dim=0)\n",
    "\n",
    "# finally, we initialize the parameter buffers and set the values.\n",
    "# since classifier is a HybridSequential/Sequential, the following\n",
    "# takes the zero-indexed 1-st layer of the classifier \n",
    "final_conv_layer_params = deep_dog_net.output[0].params\n",
    "final_conv_layer_params.get('weight').set_data(new_classifier_w)\n",
    "final_conv_layer_params.get('bias').set_data(new_classifier_b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluation\n",
    "\n",
    "Our task is a binary classification problem with imbalanced classes. So we'll monitor performance both using accuracy and F1 score, a metric favored in settings with extreme class imbalance.\n",
    "[Note to authors: ensure that F1 score is explained earlier or explain it here in full]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# return metrics string representation\n",
    "def metric_str(names, accs):\n",
    "    return ', '.join(['%s=%f'%(name, acc) for name, acc in zip(names, accs)])\n",
    "metric = mx.metric.create(['acc', 'f1'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following snippet performs inferences on evaluation dataset, and updates the metrics. Once the evaluation data iterator is exhausted, it returns the values of each of the metrics."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import mxnet.gluon as gluon\n",
    "from mxnet.image import color_normalize\n",
    "\n",
    "def evaluate(net, data_iter, ctx):\n",
    "    data_iter.reset()\n",
    "    for batch in data_iter:\n",
    "        data = color_normalize(batch.data[0]/255,\n",
    "                               mean=mx.nd.array([0.485, 0.456, 0.406]).reshape((1,3,1,1)),\n",
    "                               std=mx.nd.array([0.229, 0.224, 0.225]).reshape((1,3,1,1)))\n",
    "        data = gluon.utils.split_and_load(data, ctx_list=ctx, batch_axis=0)\n",
    "        label = gluon.utils.split_and_load(batch.label[0], ctx_list=ctx, batch_axis=0)\n",
    "        outputs = []\n",
    "        for x in data:\n",
    "            outputs.append(net(x))\n",
    "        metric.update(label, outputs)\n",
    "    out = metric.get()\n",
    "    metric.reset()\n",
    "    return out"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now can train the model just as we would any supervised model.\n",
    "In this example, we set up the training loop for multi-GPU use \n",
    "as described from first principles [here](../chapter07_distributed-learning/multiple-gpus-scratch.ipynb) and in the context of gluon [here](../chapter07_distributed-learning/multiple-gpus-gluon.ipynb)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import mxnet.autograd as autograd\n",
    "\n",
    "def train(net, train_iter, val_iter, epochs, ctx):\n",
    "    if isinstance(ctx, mx.Context):\n",
    "        ctx = [ctx]\n",
    "    trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': learning_rate, 'wd': wd})\n",
    "    loss = gluon.loss.SoftmaxCrossEntropyLoss()\n",
    "\n",
    "    best_f1 = 0\n",
    "    val_names, val_accs = evaluate(net, val_iter, ctx)\n",
    "    logging.info('[Initial] validation: %s'%(metric_str(val_names, val_accs)))\n",
    "    for epoch in range(epochs):\n",
    "        tic = time.time()\n",
    "        train_iter.reset()\n",
    "        btic = time.time()\n",
    "        for i, batch in enumerate(train_iter):\n",
    "            # the model zoo models expect normalized images\n",
    "            data = color_normalize(batch.data[0]/255,\n",
    "                                   mean=mx.nd.array([0.485, 0.456, 0.406]).reshape((1,3,1,1)),\n",
    "                                   std=mx.nd.array([0.229, 0.224, 0.225]).reshape((1,3,1,1)))\n",
    "            data = gluon.utils.split_and_load(data, ctx_list=ctx, batch_axis=0)\n",
    "            label = gluon.utils.split_and_load(batch.label[0], ctx_list=ctx, batch_axis=0)\n",
    "            outputs = []\n",
    "            Ls = []\n",
    "            with autograd.record():\n",
    "                for x, y in zip(data, label):\n",
    "                    z = net(x)\n",
    "                    # rescale the loss based on class to counter the imbalance problem\n",
    "                    L = loss(z, y) * (1+y*positive_class_weight)/positive_class_weight\n",
    "                    # store the loss and do backward after we have done forward\n",
    "                    # on all GPUs for better speed on multiple GPUs.\n",
    "                    Ls.append(L)\n",
    "                    outputs.append(z)\n",
    "                for L in Ls:\n",
    "                    L.backward()\n",
    "            trainer.step(batch.data[0].shape[0])\n",
    "            metric.update(label, outputs)\n",
    "            if log_interval and not (i+1)%log_interval:\n",
    "                names, accs = metric.get()\n",
    "                logging.info('[Epoch %d Batch %d] speed: %f samples/s, training: %s'%(\n",
    "                               epoch, i, batch_size/(time.time()-btic), metric_str(names, accs)))\n",
    "            btic = time.time()\n",
    "\n",
    "        names, accs = metric.get()\n",
    "        metric.reset()\n",
    "        logging.info('[Epoch %d] training: %s'%(epoch, metric_str(names, accs)))\n",
    "        logging.info('[Epoch %d] time cost: %f'%(epoch, time.time()-tic))\n",
    "        val_names, val_accs = evaluate(net, val_iter, ctx)\n",
    "        logging.info('[Epoch %d] validation: %s'%(epoch, metric_str(val_names, val_accs)))\n",
    "\n",
    "        if val_accs[1] > best_f1:\n",
    "            best_f1 = val_accs[1]\n",
    "            logging.info('Best validation f1 found. Checkpointing...')\n",
    "            net.save_parameters('deep-dog-%d.params'%(epoch))\n",
    "\n",
    "if mode == 'hybrid':\n",
    "    deep_dog_net.hybridize()\n",
    "if epochs > 0:\n",
    "    deep_dog_net.collect_params().reset_ctx(contexts)\n",
    "    train(deep_dog_net, train_iter, val_iter, epochs, contexts)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Try it out!\n",
    "Once our model is trained, we can either use the `deep_dog_net` model in the notebook kernel, or load it from the best checkpoint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Uncomment below line and replace the file name with the last checkpoint.\n",
    "# deep_dog_net.load_parameters('deep-dog-3.params', contexts)\n",
    "#\n",
    "# Alternatively, you can uncomment the following lines to get the model that we finetuned,\n",
    "# with validation F1 score of 0.74.\n",
    "download('https://apache-mxnet.s3-accelerate.amazonaws.com/gluon/models/deep-dog-5a342a6f.params',\n",
    "         overwrite=True)\n",
    "deep_dog_net.load_parameters('deep-dog-5a342a6f.params', contexts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "classify_hotdog(deep_dog_net, '../img/real_hotdog.jpg', contexts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "classify_hotdog(deep_dog_net, '../img/leg_hotdog.jpg', contexts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "classify_hotdog(deep_dog_net, '../img/dog_hotdog.jpg', contexts)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusions\n",
    "As you can see, given a pretrained model, we can get a great classifier, \n",
    "even for tasks where we simply don't have enough data to train from scratch.\n",
    "That's because the representations necessary to perform both tasks have a lot in common.\n",
    "Since they both address natural images, they both require recognizing textures, shapes, edges, etc.\n",
    "Whenever you have a small enough dataset that you fear impoverishing your model,\n",
    "try thinking about what larger datasets you might be able to pre-train your model on,\n",
    "so that you can just perform fine-tuning on the task at hand.\n",
    "\n",
    "\n",
    "## Next\n",
    "\n",
    "This section is still changing too fast to say for sure what will come next. Stay tuned!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For whinges or inquiries, [open an issue on  GitHub.](https://github.com/zackchase/mxnet-the-straight-dope)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
